import java.lang.reflect.Array;
import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }

        //把原始数据给到elem数组
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent, usedSize);
        }
    }

    /**
     *
     * @param parent 每棵树的根结点
     * @param len  代表每棵子树的结束
     */
    //向下调整 时间复杂度O(N)
    private void shiftDown( int parent, int len) {
        int child = 2 * parent + 1;

        while(child < len) {
            if(child + 1 < len && elem[child]  < elem[child+1]) {
                child = child+1;
            }

            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2 * parent +1;
            }
            else {
                break;
            }
        }
    }

    public void push(int val) {
        //检查满
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        //存数据
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    //向上调整时间复杂度O(N*logN)
    public void  shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }
            else {
                break;
            }
        }
    }

    //删除元素，只能删除堆顶元素
    //1.0下标和最后一个下标进行交换；2.向下调整0下标这棵树；3.此时调整结束的位置是 < usedSize-1
    public void poll() {
        if(empty()) {
            throw new HeapEmptyException("优先级队列是空的！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean empty() {
        return usedSize == 0;
    }

    public int peek() {
        if(empty()) {
            throw new HeapEmptyException("优先级队列是空！");
        }

        return elem[0];
    }

    public void heapSort() {
        int end = usedSize-1;
        while(end > 0) {
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0,end);
            end--;
        }
    }
}
